package com.xiaoyu.lanling.base.push.huawei;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.huawei.hms.push.HmsMessaging;
import com.xiaoyu.base.push.BasePushAgent;
import com.xiaoyu.base.push.PushConstants;
import com.xiaoyu.lanling.base.push.alternate.PushAlternateAgent;


import in.srain.cube.util.CLog;

public class HuaWeiPushAgent extends BasePushAgent {

    private static HuaWeiPushAgent sInstance;
    private Context mContext;
    private PushAlternateAgent.OnPushReceiver mOnPushReceiver;

    private HuaWeiPushAgent() {
        super(PushConstants.PUSH_TYPE_HUAWEI);
    }

    public static synchronized HuaWeiPushAgent getInstance() {
        if (sInstance == null) {
            sInstance = new HuaWeiPushAgent();
        }
        return sInstance;
    }

    @Override
    protected void onInitPushAgent(Context context) {
        super.onInitPushAgent(context);
    }

    @Override
    protected void tryToStartPushService(final Context context) {
        mContext = context;
        super.tryToStartPushService(context);
        HmsMessaging.getInstance(context).setAutoInitEnabled(true);
    }

    @Override
    public void onCreate(Activity activity) {
        super.onCreate(activity);
    }

    public void onNewToken(String token) {
        if (!TextUtils.isEmpty(token)) {
            onRegisterSuccess(token);
            tryToStartAlternatePushService();
        } else {
            retryOnFail("token null");
        }
    }

    private void tryToStartAlternatePushService() {
        if (mOnPushReceiver == null) {
            mOnPushReceiver = new PushAlternateAgent.OnPushReceiver() {
                @Override
                public void onPushToken(String type, String token) {
                    onRegisterAlternateSuccess(type, token);
                }

                @Override
                public void onPushError(String errorMessage) {
                    waitingAlternateRegister();
                    addGetTokenEventLog("register_alternate_result", String.valueOf(errorMessage));
                }
            };
        }
        PushAlternateAgent.getInstance().setOnPushReceiver(mOnPushReceiver);
        PushAlternateAgent.getInstance().startPushServer(mContext);
    }

    private void waitingAlternateRegister() {
        CLog.i(TAG, "waitingAlternateRegister");
        final Handler handler = new Handler(Looper.getMainLooper());
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tryToStartAlternatePushService();
            }
        }, 180000);
    }
}
